package com.xu.blog_after_end.aspect;


import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

/*
    记录web包中的所有方法的执行情况
*/
@Aspect
@Component
public class LogAspect {
    private final Logger logger = LoggerFactory.getLogger(LogAspect.class.getName());
    @Pointcut("execution(* com.xu.blog_after_end.web.*.*(..))")  // 定义切点 拦截web包下的所有方法
    public void log(){}
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){  // 方法的执行情况前置通知 输出日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();  // 获取请求信息
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();  // 请求路径
        String ip = request.getRemoteAddr();  // 请求ip
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();  // 调用的类方法
        Object[] args = joinPoint.getArgs();  // 请求参数
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        logger.info("-----请求信息是：{}-------",requestLog);   // 输出请求信息
    }
    @After("log()")
    public void doAfter(){  // 方法的执行情况后置通知 输出日志
//        logger.info("-----方法执行后-------");
    }
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterRuturn(Object result){  // 方法的返回后的通知 输出日志
        logger.info("-----返回值是：{}-------",result);
    }

    private class RequestLog{
        private String url;  // 请求路径
        private String ip;  // 请求ip
        private String classMethod;  // 调用的类方法
        private Object[] args;  // 请求参数

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
